package com.yuand.exception;

import com.yuand.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.security.SignatureException;

/**
 * springboot 全局异常捕获
 *
 * @ClassName: GlobalExceptionHandler
 * @Author: yuandong
 * @Date 2022/1/15 13:32
 *
 * 注意：handleBindException和handleMethodArgumentNotValidException这两个异常
 * 用来拦截@Validated产生的异常（当参数校验出错的时候）;
 * 必须返回500错误代码，这样前端在request.js里面才会拦截并给出错误弹框
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = RuntimeException.class)
	@ResponseBody
    public ResponseResult handler(RuntimeException e) {
        log.error("运行时异常：----------------{}", e.getMessage());
        return new ResponseResult(500,e.getMessage());
    }



	//参考  https://blog.csdn.net/qq_45848700/article/details/122319021
	//GlobalExceptionHandler 全局异常处理器会比 AccessDeniedHandler 先捕获 AccessDeniedException 异常，因此当配置了 GlobalExceptionHandler 后，会发现 AccessDeniedHandler 失效了。
	@ExceptionHandler(AccessDeniedException.class)
	public ResponseResult accessDeniedException(AccessDeniedException e) throws AccessDeniedException  {
		throw e;
	}


	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(BindException.class)
	@ResponseBody
	public ResponseResult handleBindException(BindException e){
		log.error(e.getMessage(), e);
		String message = e.getAllErrors().get(0).getDefaultMessage();

		return new ResponseResult(500, message);
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
		log.info("自定义参数异常...................");
		log.error(e.getMessage(), e);
		String message = e.getBindingResult().getFieldError().getDefaultMessage();
		return new ResponseResult(500, message);
	}
}
